package com.psp.park.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.northend.util.AppTextUtil;
import com.northend.util.StringUtil;
import com.northend.util.net.HttpManagerImpl;
import com.psp.park.controller.req.ReqCooperationRecordJsonParam;
import com.psp.park.controller.req.ReqServiceRecordJsonParam;
import com.psp.park.controller.res.bean.RParkUserFormCooperationRecordListBean;
import com.psp.park.controller.res.bean.RParkUserFormServiceRecordListBean;
import com.psp.park.controller.res.bean.RQiniuFileBean;
import com.psp.park.model.ParkUserBean;
import com.psp.park.model.ParkUserFormRecordBean;
import com.psp.park.persist.dao.ParkUserFormRecordDao;
import com.psp.park.persist.dao.UserDao;
import com.psp.park.service.JsjService;
import com.psp.park.service.QiniuService;
import com.psp.park.service.exception.ServiceException;

@Service
public class JsjServiceImpl implements JsjService {

	Logger logger = Logger.getLogger(JsjServiceImpl.class);

	@Autowired
	UserDao userImpl;

	@Autowired
	ParkUserFormRecordDao parkUserFormRecordImpl;

	@Autowired
	QiniuService qiniuServiceImpl;

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean serviceRecord(String gainDate) throws ServiceException {
		boolean flag = false;
		if (StringUtil.isEmpty(gainDate)) {
			logger.error("从金数据服务器上，推送过来的数据为空");
			return false;
		}
		JSONObject jsj = JSON.parseObject(gainDate);
		if (jsj == null) {
			logger.info("金数据转化json对象为空");
			return false;
		}

		JSONObject entry = jsj.getJSONObject("entry");
		if (entry == null) {
			logger.info("金数据转化json对象--entry属性为空");
			return false;
		}

		ReqServiceRecordJsonParam data = JSONObject.parseObject(entry.toJSONString(), ReqServiceRecordJsonParam.class);
		if (data == null) {
			logger.info("金数据转化json对象转换为空javabean为空");
			return false;
		}
		String parkAccount = data.getParkAccount();
		if (!StringUtil.isEmpty(parkAccount)) {
			parkAccount = parkAccount.trim();
		} else {
			return false;
		}
		ParkUserBean parkUser = userImpl.selectOneByAccount(parkAccount);
		if (parkUser == null) {
			return false;
		}

		ParkUserFormRecordBean record = new ParkUserFormRecordBean();
		record.setId(AppTextUtil.getPrimaryKey());
		record.setPuid(parkUser.getPuid());
		record.setUserName(data.getUserName());
		record.setContactPhone(data.getContactPhone());
		record.setContent(data.toJsonString());
		record.setType(1); // 表单类型 1需求登记 2合作登记

		flag = parkUserFormRecordImpl.insert(record) > 0;
		if (!flag) {
			logger.info("insert park_user_form_record has expection");
			return false;
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean cooperationRecord(String gainDate) throws ServiceException {
		boolean flag = false;
		if (StringUtil.isEmpty(gainDate)) {
			return false;
		}
		JSONObject jsj = JSON.parseObject(gainDate);
		if (jsj == null) {
			return false;
		}

		JSONObject entry = jsj.getJSONObject("entry");
		if (entry == null) {
			return false;
		}
		ReqCooperationRecordJsonParam data = JSONObject.parseObject(entry.toJSONString(),
				ReqCooperationRecordJsonParam.class);

		if (data == null) {
			return false;
		}
		String parkAccount = data.getParkAccount();
		if (!StringUtil.isEmpty(parkAccount)) {
			parkAccount = parkAccount.trim();
		} else {
			return false;
		}
		ParkUserBean parkUser = userImpl.selectOneByAccount(parkAccount);
		if (parkUser == null) {
			return false;
		}

		JSONArray license = data.getBusinessLicense();
		if (license != null && license.size() > 0) {
			JSONArray array = jsuToQiniu(license.toJavaList(String.class));
			data.setBusinessLicense(array);
		}

		JSONArray briefImg = data.getCompanyBriefImg();
		if (briefImg != null && briefImg.size() > 0) {
			JSONArray array = jsuToQiniu(briefImg.toJavaList(String.class));
			data.setCompanyBriefImg(array);
		}

		ParkUserFormRecordBean record = new ParkUserFormRecordBean();
		record.setId(AppTextUtil.getPrimaryKey());
		record.setPuid(parkUser.getPuid());
		record.setUserName(data.getUserName());
		record.setContactPhone(data.getContactPhone());
		record.setContent(data.toJsonString());
		record.setType(2); // 表单类型 1需求登记2合作登记

		flag = parkUserFormRecordImpl.insert(record) > 0;
		if (!flag) {
			logger.info("insert park_user_form_record has expection");
			return false;
		}

		return flag;
	}

	private JSONArray jsuToQiniu(List<String> list) {
		JSONArray array = new JSONArray();
		for (String imgUrl : list) {
			if (!StringUtil.isEmpty(imgUrl)) {
				try {
					imgUrl = new String(imgUrl.getBytes(), "UTF-8");
					byte[] value = getFileFromJSJServer(imgUrl);
					RQiniuFileBean qiniuToken = qiniuServiceImpl.uploadFile(value);
					if (qiniuToken != null) {
						array.add(qiniuToken.getUrl());
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		return array;
	}

	/**
	 * 从金数据服务器上取出文件
	 * 
	 * @param fileUrl
	 * @return
	 */
	private byte[] getFileFromJSJServer(String fileUrl) {
		byte[] value = HttpManagerImpl.getInstance().getFile(fileUrl, null);
		return value;
	}

	@Override
	public PageResult<RParkUserFormServiceRecordListBean> getRecordList(int page, int pageSize, String puid) {
		PageResult<RParkUserFormServiceRecordListBean> result = new PageResult<>();
		int count = parkUserFormRecordImpl.selectCount(puid, 1);
		List<ParkUserFormRecordBean> list = parkUserFormRecordImpl.selectList(page, pageSize, puid, 1);
		List<RParkUserFormServiceRecordListBean> resList = new ArrayList<>();

		if (list != null && list.size() > 0) {
			for (ParkUserFormRecordBean bean : list) {
				RParkUserFormServiceRecordListBean rb = new RParkUserFormServiceRecordListBean();
				rb.setId(bean.getId());
				rb.setType(bean.getType());
				rb.setContent(bean.getContent());
				rb.setCreateTime(bean.getCreateTime() != null ? bean.getCreateTime().getTime() : 0);
				resList.add(rb);
			}
		}

		result.setData(resList);
		result.setCount(count);
		return result;
	}

	@Override
	public PageResult<RParkUserFormCooperationRecordListBean> getCooperationRecordList(int page, int pageSize,
			String puid) {
		PageResult<RParkUserFormCooperationRecordListBean> result = new PageResult<>();
		int count = parkUserFormRecordImpl.selectCount(puid, 2);
		List<ParkUserFormRecordBean> list = parkUserFormRecordImpl.selectList(page, pageSize, puid, 2);
		List<RParkUserFormCooperationRecordListBean> resList = new ArrayList<>();

		if (list != null && list.size() > 0) {
			for (ParkUserFormRecordBean bean : list) {
				RParkUserFormCooperationRecordListBean rb = new RParkUserFormCooperationRecordListBean();
				rb.setId(bean.getId());
				rb.setType(bean.getType());
				rb.setContent(bean.getContent());
				rb.setCreateTime(bean.getCreateTime() != null ? bean.getCreateTime().getTime() : 0);
				resList.add(rb);
			}
		}

		result.setData(resList);
		result.setCount(count);
		return result;
	}

}
